package top.chaileilei.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @Description master选举demo
 * @Time 2019/2/12
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class MasterSelect {
    private static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("119.27.189.174:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();

    public static void main(String[] args) throws InterruptedException {
        masterSelect();
    }

    public static void masterSelect() throws InterruptedException {
        client.start();
        String path = "/dgfw";
        LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListener() {
            //竞争到master后自动调用该方法，执行完会立即释放master权利，开始新一轮的master选举。
            @Override
            public void takeLeadership(CuratorFramework client) throws Exception {
                System.out.println("111111111111");
                Thread.sleep(2000);
                System.out.println("释放掉");
            }
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState) {

            }
        });
        selector.autoRequeue();
        selector.start();
        Thread.sleep( Integer.MAX_VALUE );
    }
}
